<template>
  <div class="resa">
    <el-form :model="fromData" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <!-- <el-form-item label="显示位置">
        <el-radio-group v-model="fromData.type">
          <el-radio :label="1">公众号首页</el-radio>
          <el-radio :label="2">公众号积分商城</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <el-form-item label="图片" class="is-required">
        <div class="imgpost">
          <el-upload class="avatar-uploader" name="production" ref="upload" :action="$upUrl" :show-file-list="false" :auto-upload="false" :before-upload="beforeAvatarUpload" :on-change="changimg" accept=".jpg,.png,.jpeg">
            <div class="upimg" v-if="imageUrl" @click.stop="">
              <img :src="imageUrl" class="avatar" />
              <div>
                <div>
                  <i class="el-icon-zoom-in" @click.stop="handlePictureCardPreview(imageUrl)"></i>
                </div>
                <div>
                  <i class="el-icon-delete" @click.stop="handleRemove"></i>
                </div>
              </div>
            </div>
            <div v-else class="upback">
              <div>
                <i class="el-icon-plus elimg_icon"></i>
                <div class="elimg_text">上传图片</div>
              </div>
            </div>
          </el-upload>
          <div class="img_ps">
            支持jpg、jepg、png图片，最佳像素比例690*400。大小请控制在1M以内。
          </div>
        </div>

        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="imageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="fromData.name"></el-input>
      </el-form-item>
      <el-form-item label="显示位置" prop="big_type_id">
        <el-select v-model="fromData.big_type_id">
          <el-option :value="0" label="推荐"></el-option>
          <el-option :value="1" label="看书"></el-option>
          <el-option :value="2" label="听书"></el-option>
          <el-option :value="3" label="汇画"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="跳转方式" prop="skip_way">
        <el-select v-model="fromData.skip_way" @change="skipWayChange">
          <el-option :value="1" label="H5链接"></el-option>
          <el-option :value="2" label="每日荐读"></el-option>
          <el-option :value="3" label="主题书单"></el-option>
          <el-option :value="4" label="资源详情"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="跳转链接" v-if="fromData.skip_way==1">
        <el-input v-model="fromData.link"></el-input>
      </el-form-item>

      <el-form-item label="每日荐读" v-if="fromData.skip_way==2" prop="link">
        <el-select v-model="fromData.link">
          <el-option :label="item.name" :value="item.id" v-for="item in filterList" style="min-width:500px"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="阅读书单" v-if="fromData.skip_way==3" prop="link">
        <el-select v-model="fromData.link" style="min-width:500px">
          <el-option :label="item.name" :value="item.id" v-for="item in filterList"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="资源详情" v-if="fromData.skip_way==4" prop="link">
        <el-select style="min-width:500px" v-model="fromData.link" :remote="true" :loading="searchLoading" :filter-method="getBookList" filterable clearable>
          <el-option :label="item.name" :value="item.id" v-for="item in filterList"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="fromData.sort"></el-input-number>
      </el-form-item>

      <el-form-item>
        <div style="padding: 100px 0 0 0" class="btn_el">
          <el-button @click="submitForm('ruleForm')" class="btn_establish">
            确认
          </el-button>
          <el-button class="btn_cancel" @click="can">取消</el-button>
        </div>
      </el-form-item>
    </el-form>
    <!-- vueCropper 剪裁图片实现-->
    <x-cropperFixed ref="iscropper" :uploadImg="uploadImgs" @cropPicture="cropPicture" :cropImg="cropImg"></x-cropperFixed>
  </div>
</template>

<script>
import { isConfiguration } from 'config/env.js'
export default {
  data() {
    return {
      ruleForm: {
        name: '',
        type: 1
      },
      dialogVisible: false,
      rules: {
        imgurl: [
          { required: true, message: '请输入上传图片', trigger: 'blur' }
        ],
        name: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        big_type_id: [{ required: true, message: '请选择显示位置', trigger: 'blur' }],
        skip_way: [{ required: true, message: '请选择跳转方式', trigger: 'blur' }],
        link: [{ required: true, message: '', trigger: 'blur' }],
      },
      unimgurl: '',
      imageUrl: '',
      library: [],
      cropImg: 'cropImg20',
      uploadImgs: '',
      isConfiguration: undefined,
      filterList: [],
      searchLoading: false
    }
  },
  props: ['fromData'],
  watch: {
    fromData: {
      deep: true,
      // 修改时部分数据回溯
      handler(val, oldVal) {
        // 监听外部的图片是否请求完毕
        if (val.img != oldVal.img) {
          this.imageUrl = this.$img(this.fromData.img);


          if (val.skip_way == 4) {
            console.log(val);
            
            this.getBookList(val.link_name)
          } else if ([2, 3].includes(val.skip_way)) {
            this.$nextTick(() => {
              this.fromData.link = +this.fromData.link
            })

            this.skipWayChange(val.skip_way, false)
          }
        }
      },

    },
    // 要剪裁图片
    uploadImgs(nal, al) {
      this.uploadImgs = nal
    }
  },
  mounted() { },
  created() { },
  activated() {
    this.isConfiguration = isConfiguration
    if (this.$route.query.action) {
      if (this.$route.query.action != 'refresh') {
        this.unimgurl = ''
        this.imageUrl = ''
      }
    } else {
      this.unimgurl = ''
      this.imageUrl = ''
    }
  },
  methods: {
    skipWayChange(way, canReset = true) {
      this.filterList = JSON.parse(JSON.stringify([]))

      if (canReset) {
        this.fromData = { ...this.fromData, link: '' }
      }
      if (way == 1) { }
      else if (way == 2) {
        this.getRecomList()
      }
      else if (way == 3) {
        this.getThemeListBookList()
      }
      
    },
    // 荐读筛选
    getRecomList() {
      this.request({ url: 'admin/resourceReadRecom/filterList' }).then(res => {
        this.filterList = res.content
      }).catch(e => this.errorHandler(e))
    },
    // 主题书单筛选
    getThemeListBookList() {
      this.request({ url: 'admin/resourceReadingList/filterList' }).then(res => {
        this.filterList = res.content
      }).catch(e => this.errorHandler(e))
    },
    // 书籍筛选
    getBookList(keywords) {
      console.log(keywords);
      
      if (typeof keywords != 'string') return
      this.searchLoading = true
      this.request({
        url: 'admin/resourceTotal/filterList', data: {
          keywords,
          limit: 100
        },
        loading: false
      }).then(res => {
        this.searchLoading = false
        this.filterList = res.content.map(item => {
          return {
            name: item.title,
            id: item.guid
          }
        })
      }).catch(e => {
        console.log(e.toString().includes(203))
        if (e.toString().includes(203)) {
          this.filterList = JSON.parse(JSON.stringify([]))
          this.searchLoading = false
        }
        this.errorHandler(e)
      })
    },

    beforeAvatarUpload(file) {
      console.log(file)
      const isJPG = file.type === 'image/jpg' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 <= 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    //删除封面图
    handleRemove(file, fileList) {
      this.imageUrl = ''
      this.unimgurl = ''
      this.fromData.imgurl = ''
      this.fromData.img = ''
    },
    //选择封面图
    handlePictureCardPreview(img) {
      this.imageUrl = img
      this.dialogVisible = true
    },
    changimg(file) {
      const isLt2M = file.size / 1024 / 1024 <= 1
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 1MB!')
      } else {
        let that = this
        const fr = new FileReader()
        fr.readAsDataURL(file.raw)
        fr.onload = function () {
          // console.log(fr.result);
          return (that.uploadImgs = fr.result)
        }
        setTimeout(() => {
          this.$refs.iscropper.showModal({
            cutWidth: 345, // 默认生成截图框宽度
            cutHeight: 200, // 默认生成截图框高度
            rate: '690:400',
            file: file.raw
          })
        }, 100)
      }
    },
    // 裁剪返回参数
    cropPicture(imgUrl) {
      this.unimgurl = imgUrl.file
      this.imageUrl = imgUrl.dataURL
      this.fromData.imgurl = imgUrl.file
    },
    //上传图片
    async uploadImg() {
      try {
        let imgRes = await this.request({
          url: '/uploads/files',
          method: 'post',
          dataType: 'blob',
          loading: true,
          data: {
            banner: this.unimgurl
          }
        })
        if (imgRes) {
          this.fromData.img = imgRes.content.img
          this.$emit('btn_submit', this.fromData)
        }
      } catch (err) {
        this.errorHandler(err)
      }
    },
    can() {
      this.$router.push({
        path: '/ImageManagement/publicBanner'
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(this.unimgurl);

          if (this.unimgurl) {
            this.uploadImg()
          } else {
            // this.$message.error('请添加图片')
            if (this.fromData.img) {
              this.$emit('btn_submit', this.fromData)
            } else {
              this.$message.error('请添加图片')
            }
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "./style.scss";
</style>
<style lang="scss">
.resa {
  .is-checked {
    > span {
      // color: #1bc992 !important;
    }
  }
}

.from_swt {
  .tableScopeSwitchA {
    width: 66px !important;
    height: 26px !important;
    line-height: 26px !important;
    border-radius: 13px !important;
  }
  .tableScopeSwitchA .el-switch__label {
    position: absolute;
    display: none;
    color: #fff;
    width: 66px !important;
    height: 26px !important;
    line-height: 26px !important;
    border-radius: 13px !important;
  }
  /*打开时文字位置设置*/
  .tableScopeSwitchA .el-switch__label--right {
    z-index: 1;
    right: -14px; /*不同场景下可能不同，自行调整*/
    font-size: 12px;
    font-family: Microsoft YaHei, Microsoft YaHei-Regular;
    font-weight: 400;
    color: #ffffff;
  }
  /*关闭时文字位置设置*/
  .tableScopeSwitchA .el-switch__label--left {
    z-index: 1;
    left: 20px; /*不同场景下可能不同，自行调整*/
    font-size: 12px;
    font-family: Microsoft YaHei, Microsoft YaHei-Regular;
    font-weight: 400;
    color: #fff;
  }
  /*显示文字*/
  .tableScopeSwitchA .el-switch__label.is-active {
    display: block;
  }
  .tableScopeSwitchA.el-switch .el-switch__core,
  .el-switch .el-switch__label {
    width: 70px !important; /*开关按钮的宽度大小*/
    height: 20px !important;
    line-height: 20px !important;
    border-radius: 13px !important;
  }
  .el-switch__core:after {
    top: 1px;
  }
}
</style>
